<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/29
 * Time: 16:26
 */

namespace app\common\lib;


use app\exception\IndexException;
use GuzzleHttp\Client;
use QL\Ext\Chrome;
use QL\QueryList;

class Puppeteer
{
    protected static $instance;

    protected $userAgents;
    protected $userAgentsPc;

    public function __construct()
    {
        $this->userAgents = [
            'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
            'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36',
            'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
            'Mozilla/5.0 (Linux; U; Android 9; zh-cn; Redmi Note 5 Build/PKQ1.180904.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.10.8',
            'Mozilla/5.0 (Linux; Android 9; MI 6 Build/PKQ1.190118.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.89 Mobile Safari/537.36 T7/11.20 SP-engine/2.16.0 baiduboxapp/11.20.2.3 (Baidu; P1 9)',
            'Mozilla/5.0 (Linux; Android 10; VCE-AL00 Build/HUAWEIVCE-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.186 Mobile Safari/537.36 baiduboxapp/11.0.5.12 (Baidu; P1 10)',
            'Mozilla/5.0 (Linux; Android 10; CLT-AL00 Build/HUAWEICLT-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.89 Mobile Safari/537.36 T7/11.20 SP-engine/2.16.0 baiduboxapp/11.20.0.14 (Baidu; P1 10) NABar/1.0',
            'Mozilla/5.0 (Linux; U; Android 6.0.1; zh-cn; OPPO A57 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/9.1 Mobile Safari/537.36',
            'Mozilla/5.0 (Linux; U; Android 9; zh-CN; LON-AL00 Build/HUAWEILON-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.9.0.1070 Mobile Safari/537.36',
            'Mozilla/5.0 (Linux; Android 10; YAL-AL00 Build/HUAWEIYAL-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.89 Mobile Safari/537.36 T7/11.20 SP-engine/2.16.0 baiduboxapp/11.20.0.14 (Baidu; P1 10) NABar/2.0',
            'Mozilla/5.0 (Linux; Android 10; SM-G9750 Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.89 Mobile Safari/537.36 T7/11.19 SP-engine/2.15.0 baiduboxapp/11.19.5.10 (Baidu; P1 10)',
            'Mozilla/5.0 (Linux; U; Android 9; zh-cn; PACT00 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/10.1 Mobile Safari/537.36',
            'Mozilla/5.0 (Linux; U; Android 9; zh-cn; Redmi 7 Build/PKQ1.181021.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.8.14',
            'Mozilla/5.0 (Linux; U; Android 9; zh-cn; INE-AL00 Build/HUAWEIINE-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/10.1 Mobile Safari/537.36'
        ];

        $this->userAgentsPc = [
            'User-Agent,Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'User-Agent,Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'User-Agent,Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;',
            'User-Agent,Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
            'User-Agent,Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
            'User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
            'User-Agent,Mozilla/5.0 (Windows NT 6.1; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
            'User-Agent,Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
            'User-Agent,Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
            'User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
            'User-Agent,Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
        ];
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }


        return new self();
    }

    public function getVideoLink($shareText)
    {
        //抖音app分享
//        $shareText = '1.25 复制打开抖音，看看【小鱼和小游的作品】让我开了眼界 他是真行啊 # 搞笑夫妻 # 婚后生... https://v.douyin.com/iNv7dMBd/ 04/03 E@h.bn Okc:/';
//        //抖音pc分享
//        $shareText = '2.51 tEU:/ 07/26 a@a.At 让我开了眼界 他是真行啊 # 搞笑夫妻 # 婚后生活 # 你们的男友也是这样吗 # 万万想不到 # 离谱  https://v.douyin.com/iFJDHJNU/ 复制此链接，打开Dou音搜索，直接观看视频！';
//
//        //快手app分享
//        $shareText = 'https://v.kuaishou.com/o6CwHu  斯诺克后继有人"斯诺克 "斯佳辉 该作品在快手被播放过221.8万次，点击链接，打开【快手】直接观看！';
//        //快手pc分享
//        $shareText = 'https://www.kuaishou.com/f/X-KqCixy12zX1bV';
//
//        //哔哩哔哩app分享
//        $shareText = '【【广州地铁那些事Ⅶ】那些或鲜为人知或广为流传的废弃预留你又知多少？挖掘广州地铁1、2、8号线的废弃预留-哔哩哔哩】 https://b23.tv/cGjy1HQ';
//        //哔哩哔哩pc分享
//        $shareText = '【【广州地铁那些事Ⅶ】那些或鲜为人知或广为流传的废弃预留你又知多少？挖掘广州地铁1、2、8号线的废弃预留】 https://www.bilibili.com/video/BV1zC41147vZ/?share_source=copy_web';
//
//        //小红书app分享
//        $shareText = '45 烈火狂歌发布了一篇小红书笔记，快来看吧！ 😆 cNtpZP49LFOovJu 😆 http://xhslink.com/Va22wC，复制本条信息，打开【小红书】App查看精彩内容！';
//        //小红书pc分享
//        $shareText = '80 【有意思吧 - 烈火狂歌 | 小红书 - 你的生活指南】 😆 HeEJKtLKGw2Esz1 😆 http://xhslink.com/hdUK4E';
//
//        //新浪微博app分享
//        $shareText = 'https://video.weibo.com/show?fid=1034:5016939945197602';
//        //        //新浪微博pc分享
//        //        $shareText = 'http://t.cn/A6joL2EQ';
//        //
//        //西瓜app分享
//        $shareText = 'https://v.ixigua.com/iFJUpJcL/点击链接直接打开';
//        //西瓜pc分享
//        $shareText = 'https://www.ixigua.com/7341817709371654697';
//
//        //头条app分享
//        $shareText = 'https://m.toutiao.com/is/iNTBn7SQ/ - 谢谢国航，看看飞机上白金卡大佬的服务，乘务长亲自来问候#空姐 - 今日头条 - 今日头条';
//        //头条pc分享
//        $shareText = 'https://www.toutiao.com/video/7323902941042213415/';
//        //
//        //好看app分享
//        $shareText = 'https://haokan.hao123.com/v?vid=11846885951787884548&pd=haokan_share&context=%7B%22cuid%22%3A%22l8HRa_a3Hagx8H80la2N8j8QvagQaH8xga-Qa_ugHf8jkLag_iS6azAPA%22%7D';
//        //好看pc分享
//        $shareText = 'https://haokan.baidu.com/v?vid=12849841621539735246&';


        $preg = '/http[s]?:\/\/[\w|\/|\.|\-|=|\?|:|%|&]+/';
        preg_match_all($preg,$shareText,$data);
        //var_dump($data[0][0]);
        $videoLink = '';
        if(!empty($data[0][0])){
            $url = $data[0][0];
            try{
                if(strpos($url,'douyin.com/')){
                    $videoLink = Puppeteer::getInstance()->douyinVideoByMobile($url);
                }elseif(strpos($url,'kuaishou.com/')){
                    $videoLink = Puppeteer::getInstance()->kuaishouVideoByPc($url);
                }elseif(strpos($url,'b23.tv/') || strpos($url,'bilibili.com/')){
                    $videoLink = Puppeteer::getInstance()->bilibiliVideoByMobile($url);
                }elseif(strpos($url,'xhslink.com/')){
                    $videoLink = Puppeteer::getInstance()->xiaohoneshuVideoByPc($url);
                }elseif(strpos($url,'video.weibo.com/') || strpos($url,'t.cn/')){
                    $videoLink = Puppeteer::getInstance()->weiboVideoByApi($url);
                }elseif(strpos($url,'ixigua.com/')){
                    $videoLink = Puppeteer::getInstance()->xiguaVideoByMobile($url);
                }elseif(strpos($url,'toutiao.com/')){
                    $videoLink = Puppeteer::getInstance()->toutiaoVideoByPc($url);
                }elseif(strpos($url,'hao123.com/') || strpos($url,'baidu.com/')){
                    $url = str_replace('baidu.com','hao123.com',$url);
                    $videoLink = Puppeteer::getInstance()->haokanVideoByPc($url);
                }
            }catch (\Exception $e){
                throw new IndexException($e->getCode(),$e->getMessage());
            }
        }else{
            throw new IndexException(4020,'视频链接错误');
        }
        //var_dump($videoLink);

        if($videoLink==false){
            throw new IndexException(4020,'链接提取视频失败,请稍后再试');
        }
        return $videoLink;
    }

    //抖音视频
    public function douyinVideoByMobile($url,$nums = 0)
    {
        if($url==false){
            return '';
        }
        $fileName = 'videohtml/douyin_video_play_cookie.txt';
        $cookiesData = [];
        if(is_file(runtime_path($fileName))){
            $cookie = file_get_contents(runtime_path($fileName));
            $cookies = explode(';',$cookie);
            foreach($cookies as $val){
                $val = trim($val);
                $key = substr($val,0,strpos(trim($val),'='));
                $value = substr($val,strpos(trim($val),'=')+1);
                $cookiesData[$key] = $value;
            }
        }
        //var_dump($cookiesData);

        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(Chrome::class, 'chrome');

        try{
            $html = $ql->chrome(function ($page, $browser) use ($url,$cookiesData,$fileName) {
                $page->setUserAgent($this->userAgents[rand(0,count($this->userAgents)-1)]);
                // 设置cookie
                $page->setCookie([
                    'name' => '_tea_utm_cache_1243',
                    'value' => $cookiesData['_tea_utm_cache_1243']??'',
                    'domain' => '.douyin.com',
                    'path' => '/'
                ],[
                    'name' => 'msToken',
                    'value' => $cookiesData['msToken']??'',
                    'domain' => '.douyin.com',
                    'path' => '/'
                ]);

                $page->goto($url);

                //$page->waitFor('video');
                $html = $page->content();
                //$page->setViewport(['width' => 2000, 'height' => 1000]);
                $cookie = $page->evaluate(
                    'document.cookie'
                );

                file_put_contents(runtime_path($fileName),$cookie);
                //var_dump($cookie);

                //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
                sleep(5);
                $browser->close();

                // 返回值一定要是页面的HTML内容
                return $html;
            }, [
                'headless' => true, // 启动可视化Chrome浏览器,方便调试
                'devtools' => true, // 打开浏览器的开发者工具
                'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
            ])->getHtml();
        }catch (\Exception $e){
            $nums++;
            if($nums>3){
                return '';
            }else{
                sleep(1);
                return $this->douyinVideoByMobile($url,$nums);
            }
        }

        $fileName = 'videohtml/douyin_video_play_mobile_html.html';
        Common::mkdirs(dirname(runtime_path($fileName)));
        file_put_contents(runtime_path($fileName), $html);
        $html = file_get_contents(runtime_path($fileName));
        $ql = QueryList::html($html);
        $data = $ql->find('video')->attrs('src');

        $videoPath = $data->all()[0]??'';
        $videoLink = '';
        if($videoPath){
            $queryString = parse_url($videoPath,PHP_URL_QUERY);
            $videoLink = 'https://www.douyin.com/aweme/v1/play/?'.$queryString;

            @unlink(runtime_path($fileName));
        }
        if($videoLink==false){
            $nums++;
            if($nums>3){
                return '';
            }else{
                sleep(1);
                return $this->douyinVideoByMobile($url,$nums);
            }
        }
        return $videoLink;
    }

    //快手视频
    public function kuaishouVideoByPc($url,$num=1)
    {
        if($url==false){
            return '';
        }

        $url = str_replace('//www.','//v.',$url);
        $fileName = 'videohtml/kuaishou_video_html_'.Common::randString(6,1).'.html';

        $cookieFileName = 'videohtml/kuaishou_video_play_cookie.txt';
        $cookiesData = [];
        $cookieContent = '';
        if(is_file(runtime_path($cookieFileName))){
            $cookieContent = file_get_contents(runtime_path($cookieFileName));
            //var_dump($cookieContent);
            $cookies = explode(';',$cookieContent);
            foreach($cookies as $val){
                $val = trim($val);
                $key = substr($val,0,strpos(trim($val),'='));
                $value = substr($val,strpos(trim($val),'=')+1);
                $cookiesData[$key] = $value;
            }
        }
        //var_dump($cookiesData);exit;

        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(Chrome::class, 'chrome');

        $text = $ql->chrome(function ($page, $browser) use ($url,$fileName,$cookiesData,$cookieFileName,$cookieContent) {
            $userAgentsPc = $this->userAgentsPc[rand(0,count($this->userAgentsPc)-1)];
            $page->setUserAgent($userAgentsPc);
            // 设置cookie
            $page->setCookie([
                'name' => 'apdid',
                'value' => $cookiesData['apdid']??'2b1325c6-2722-4d31-87e0-070b6926d5466ea7f754c0ffa933ef3f30f03e68b52b:1690421587:1',
                'domain' => '.kuaishou.com',
                'path' => '/'
            ],[
                'name' => 'didv',
                'value' => $cookiesData['didv']??'1709188828000',
                'domain' => '.kuaishou.com',
                'path' => '/'
            ],[
                'name' => 'kpf',
                'value' => $cookiesData['kpf']??'PC_WEB',
                'domain' => '.www.kuaishou.com',
                'path' => '/'
            ],[
                'name' => 'clientid',
                'value' => $cookiesData['clientid']??'3',
                'domain' => '.www.kuaishou.com',
                'path' => '/'
            ],[
                'name' => 'did',
                'value' => $cookiesData['did']??'web_93f651ef6686788420c25e64a785eb8d',
                'domain' => '.kuaishou.com',
                'path' => '/'
            ],[
                'name' => 'kpn',
                'value' => $cookiesData['kpn']??'KUAISHOU_VISION',
                'domain' => '.www.kuaishou.com',
                'path' => '/'
            ]);
            $page->goto($url);

            //$page->setViewport(['width' => 2000, 'height' => 1000]);
            $cookie = $page->evaluate(
                'document.cookie'
            );
            //file_put_contents(runtime_path($cookieFileName),$cookie);
            //var_dump($cookie);

            //$page->waitFor('video');
            //$page->waitForXPath('//video[contains(@src, \'https://\')]');

            //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            sleep(5);

            $html = $page->content();

            $urlLink = $page->url();
            //var_dump($urlLink);

            $headers = [
                'User-Agent'=>$userAgentsPc,
                'Cookie'=>$cookieContent?:'apdid=2b1325c6-2722-4d31-87e0-070b6926d5466ea7f754c0ffa933ef3f30f03e68b52b:1690421587:1; kpf=PC_WEB; clientid=3; did=web_93f651ef6686788420c25e64a785eb8d; didv=1719365014000; kpn=KUAISHOU_VISION',
            ];

            $path = str_replace(['https://www.kuaishou.com/'],[''],$urlLink);
            //var_dump($path);
            $guzzle = new Client(['base_uri' => 'https://www.kuaishou.com/', 'timeout'  => 10, 'verify' => false]);
            $response = $guzzle->get($path, ['headers' => $headers]);
            $contentHtml = $response->getBody()->getContents();
            //var_dump($content1);
            Common::mkdirs(dirname(runtime_path($fileName)));
            file_put_contents(runtime_path($fileName),$contentHtml);

            $browser->close();

            // 返回值一定要是页面的HTML内容
            return $html;
        }, [
            'headless' => true, // 启动可视化Chrome浏览器,方便调试
            'devtools' => true, // 打开浏览器的开发者工具
            'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
        ])->getHtml();

        //file_put_contents(runtime_path('videohtml/1111.html'),$text);

        $html = file_get_contents(runtime_path($fileName));
        $ql = QueryList::html($html);
        $data = $ql->find('script')->texts();
        $texts = $data->all();
        //var_dump($texts);

        $videoLink = '';
        foreach($texts as $text){
            if(strpos($text,'__APOLLO_STATE__')){
                $text = str_replace(['window.__APOLLO_STATE__=',';(function(){var s;(s=document.currentScript||document.scripts[document.scripts.length-1]).parentNode.removeChild(s);}());'],'',$text);

                $videoData = json_decode($text,true);
                //var_dump($videoData);
                if(!empty($videoData['defaultClient'])){
                    $k = '';
                    foreach($videoData['defaultClient'] as $key=>$val){
                        if(strpos($key,'VisionVideoDetailPhoto')!==false){
                            $k = $key;
                            break;
                        }
                    }
                    $videoLink = $videoData['defaultClient'][$k]['photoUrl']??'';
                    $videoLink==false && $videoLink = $videoData['defaultClient'][$k]['photoH265Url']??'';
                    //var_dump($videoLink);
                }
            }
        }

       @unlink(runtime_path($fileName));

        return $videoLink;
    }

    //哔哩哔哩视频
    public function bilibiliVideoByMobile($url)
    {
        if($url==false){
            return '';
        }
        $cookiesData = [];
        //        $cookie = file_get_contents(storage_path('bilibili_video_play_cookie.txt'));
        //        $cookies = explode(';',$cookie);
        //        foreach($cookies as $val){
        //            $val = trim($val);
        //            $key = substr($val,0,strpos(trim($val),'='));
        //            $value = substr($val,strpos(trim($val),'=')+1);
        //            $cookiesData[$key] = $value;
        //        }
        //var_dump($cookiesData);exit;

        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(Chrome::class, 'chrome');

        $text = $ql->chrome(function ($page, $browser) use ($url,$cookiesData) {
            $page->setUserAgent($this->userAgents[rand(0,count($this->userAgents)-1)]);
            // 设置cookie
            //            $page->setCookie([
            //                'name' => 'b_nut',
            //                'value' => $cookiesData['b_nut']??'',
            //                'domain' => '.bilibili.com',
            //                'path' => '/'
            //            ],[
            //                'name' => 'buvid3',
            //                'value' => $cookiesData['buvid3']??'',
            //                'domain' => '.bilibili.com',
            //                'path' => '/'
            //            ]);
            $page->goto($url);

            $page->waitFor('video');
            $html = $page->content();
            //$page->setViewport(['width' => 2000, 'height' => 1000]);
            //            $cookie = $page->evaluate(
            //                'document.cookie'
            //            );

            //            file_put_contents(storage_path('douyin_leader_cookie.txt'),$cookie);
            //            var_dump($cookie);


            //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            sleep(10);
            $browser->close();

            // 返回值一定要是页面的HTML内容
            return $html;
        }, [
            'headless' => true, // 启动可视化Chrome浏览器,方便调试
            'devtools' => true, // 打开浏览器的开发者工具
            'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
        ])->getHtml();

        $fileName = 'videohtml/bilibili_video_play_html.html';
        file_put_contents(runtime_path($fileName), $text);

        $html = file_get_contents(runtime_path($fileName));
        $ql = QueryList::html($html);
        $data = $ql->find('video')->attrs('src');
        $videoLink = $data->all()[0]??'';
       @unlink(runtime_path($fileName));

        return $videoLink;
    }

    //小红书视频
    public function xiaohoneshuVideoByPc($url)
    {
        if($url==false){
            return '';
        }
        $cookiesData = [];

        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(Chrome::class, 'chrome');

        $text = $ql->chrome(function ($page, $browser) use ($url,$cookiesData) {
            $page->setUserAgent($this->userAgentsPc[rand(0,count($this->userAgentsPc)-1)]);
            // 设置cookie
            $page->goto($url);

            $page->waitFor('video');
            $html = $page->content();
            //$page->setViewport(['width' => 2000, 'height' => 1000]);
            //            $cookie = $page->evaluate(
            //                'document.cookie'
            //            );

            //            file_put_contents(storage_path('douyin_leader_cookie.txt'),$cookie);
            //            var_dump($cookie);


            //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            sleep(10);
            $browser->close();

            // 返回值一定要是页面的HTML内容
            return $html;
        }, [
            'headless' => true, // 启动可视化Chrome浏览器,方便调试
            'devtools' => true, // 打开浏览器的开发者工具
            'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
        ])->getHtml();

        $fileName = 'videohtml/xiaohongshu_video_play_html.html';
        file_put_contents(runtime_path($fileName), $text);
        Common::mkdirs(runtime_path($fileName));
        $html = file_get_contents(runtime_path($fileName));
        $ql = QueryList::html($html);
        $data = $ql->find('video')->attrs('src');
        $videoLink = $data->all()[0]??'';
        @unlink(runtime_path($fileName));

        return $videoLink;
    }

    //新浪微博视频
    public function weiboVideoByApi($url)
    {
        if($url==false){
            return '';
        }
        $queryString = parse_url($url,PHP_URL_QUERY);
        parse_str($queryString,$querys);

        if(empty($querys['fid'])){
            return '';
        }
        $url = "https://weibo.com/tv/api/component?page=/tv/show/".$querys['fid'];
        $paramStr = 'data={"Component_Play_Playinfo":{"oid":"'.$querys['fid'].'"}}';
        $headers = [
            "Accept: application/json, text/plain, */*",
            "Accept-Encoding: gzip, deflate, br, zstd",
            "Accept-Language: zh-CN,zh;q=0.9",
            "Cache-Control: no-cache",
            "Content-Length: 64",
            "Content-Type: application/x-www-form-urlencoded",
            "Cookie: SINAGLOBAL=909012670454.321.1656990365673; SUB=_2AkMTRlcUf8NxqwJRmfkRxGPibYl1zArEieKlGqbPJRMxHRl-yT9vqk1atRB6OMZ5-3jDP1uPM11GNlqvRzUmrFaqdJPw; WBPSESS=rcUsgxdBPA3YG5ZaoysyzNYZs12J7nac_xwag6j1PhNS1VzzS4KSP6W6jz5_rHglChgTgA_g6WbF91SfWmK0DHM7pREGzqzNKgyyPU8tBZmX0UAwEcnTJY_3mrmYP7nDfQ5VLl7zVqZX_oBQbckByEuImZU1f5VOwTz-G9XlgWE=; UOR=,,www.baidu.com; _s_tentry=-; Apache=2393367484946.7666.1709255751244; ULV=1709255751346:2:1:2:2393367484946.7666.1709255751244:1709196677203; XSRF-TOKEN=ro7QEqqLSUBR9TLrHcKERDtu",
            "Origin: https://weibo.com",
            "Page-Referer: /tv/show/1034:4999098399391775",
            "Pragma: no-cache",
            "Referer: https://weibo.com/tv/show/1034:4999098399391775?from=old_pc_videoshow",
            'Sec-Ch-Ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
            "Sec-Ch-Ua-Mobile: ?0",
            'Sec-Ch-Ua-Platform: "Windows"',
            "Sec-Fetch-Dest: empty",
            "Sec-Fetch-Mode: cors",
            "Sec-Fetch-Site: same-origin",
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
            "X-Xsrf-Token: ro7QEqqLSUBR9TLrHcKERDtu",
            "authority: weibo.com",
            "content-type: application/x-www-form-urlencoded",
            "method: POST",
            "path: /tv/api/component?page=/tv/show/1034:4999098399391775",
            "scheme: https"
        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $paramStr,
            CURLOPT_HTTPHEADER => $headers,
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            //echo "cURL Error #:" . $err;
            return '';
        }
        $data = json_decode($response,true);
        $videoLink = array_pop($data['data']['Component_Play_Playinfo']['urls']);
        $videoLink = (strpos($videoLink,'http:')===false?'http:':'').$videoLink;
        //var_dump($videoLink);exit;

        $curl = curl_init();

        curl_setopt_array($curl, [
            //CURLOPT_URL => "http://f.video.weibocdn.com/o0/mkXC4Wkylx08cncEw54I0104120027mV0E010.mp4?label=mp4_ld&template=360x640.24.0&media_id=4999098399391775&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=4&ot=v&ps=3lckmu&uid=3ZoTIp&ab=,3601-g32,3601-g31,8013-g0,3601-g31,3601-g36,3601-g36&Expires=1709280881&ssig=fCJvdgqq3H&KID=unistore,video",
            CURLOPT_URL => $videoLink,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => $paramStr,
            CURLOPT_HTTPHEADER => $headers,
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return '';
            //echo "cURL Error #:" . $err;
        } else {
            $fileName = 'videohtml/weibo_video_mp4_'.uniqid().'.mp4';
            Common::mkdirs(dirname(runtime_path($fileName)));
            $response && file_put_contents(runtime_path($fileName),$response);

            //@unlink(runtime_path($fileName));
            return runtime_path($fileName);
        }
    }

    //西瓜视频
    public function xiguaVideoByMobile($url)
    {
        if($url==false){
            return '';
        }
        $cookiesData = [];

        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(Chrome::class, 'chrome');

        $text = $ql->chrome(function ($page, $browser) use ($url,$cookiesData) {
            $page->setUserAgent($this->userAgents[rand(0,count($this->userAgents)-1)]);

            $page->goto($url);

            $page->waitFor('video');
            $html = $page->content();
            //$page->setViewport(['width' => 2000, 'height' => 1000]);
            //            $cookie = $page->evaluate(
            //                'document.cookie'
            //            );

            //            file_put_contents(storage_path('douyin_leader_cookie.txt'),$cookie);
            //            var_dump($cookie);

            //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            sleep(6);
            $browser->close();

            // 返回值一定要是页面的HTML内容
            return $html;
        }, [
            'headless' => true, // 启动可视化Chrome浏览器,方便调试
            'devtools' => true, // 打开浏览器的开发者工具
            'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
        ])->getHtml();

        $fileName = 'videohtml/xigua_video_play_html.html';
        Common::mkdirs(dirname(runtime_path($fileName)));
        file_put_contents(runtime_path($fileName), $text);

        $html = file_get_contents(runtime_path($fileName));
        $ql = QueryList::html($html);
        $data = $ql->find('video')->attrs('src');
        $videoLink = $data->all()[0]??'';
        $videoLink && preg_match('/^\/\//',$videoLink) && $videoLink = ('https:'.$videoLink);
        $videoLink && @unlink(runtime_path($fileName));

        return $videoLink;
    }

    //今日头条视频
    public function toutiaoVideoByPc($url)
    {
        if($url==false){
            return '';
        }
        $cookiesData = [];

        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(Chrome::class, 'chrome');

        $text = $ql->chrome(function ($page, $browser) use ($url,$cookiesData) {
            $page->setUserAgent($this->userAgentsPc[rand(0,count($this->userAgentsPc)-1)]);

            $page->goto($url);

            $page->waitFor('video');
            $html = $page->content();
            //$page->setViewport(['width' => 2000, 'height' => 1000]);

            //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            sleep(6);
            $browser->close();

            // 返回值一定要是页面的HTML内容
            return $html;
        }, [
            'headless' => true, // 启动可视化Chrome浏览器,方便调试
            'devtools' => true, // 打开浏览器的开发者工具
            'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
        ])->getHtml();

        $fileName = 'videohtml/toutiao_video_play_html.html';
        Common::mkdirs(dirname(runtime_path($fileName)));
        file_put_contents(runtime_path($fileName), $text);

        $html = file_get_contents(runtime_path($fileName));
        $ql = QueryList::html($html);
        $data = $ql->find('video')->attrs('src');
        $videoLink = $data->all()[0]??'';
        $videoLink && @unlink(runtime_path($fileName));

        return $videoLink;
    }

    //好看视频
    public function haokanVideoByPc($url)
    {
        if($url==false){
            return '';
        }
        $fileName = 'videohtml/haokan_video_play_cookie.txt';
        $cookiesData = [];
        if(is_file(runtime_path($fileName))){
            $cookie = file_get_contents(runtime_path($fileName));
            $cookies = explode(';',$cookie);
            foreach($cookies as $val){
                $val = trim($val);
                $key = substr($val,0,strpos(trim($val),'='));
                $value = substr($val,strpos(trim($val),'=')+1);
                $cookiesData[$key] = $value;
            }
        }
        //var_dump($cookiesData);exit;

        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(Chrome::class, 'chrome');

        $text = $ql->chrome(function ($page, $browser) use ($url,$cookiesData,$fileName) {
            $page->setUserAgent($this->userAgentsPc[rand(0,count($this->userAgentsPc)-1)]);
            // 设置cookie
            $page->setCookie([
                'name' => 'BAIDUID',
                'value' => $cookiesData['BAIDUID']??'',
                'domain' => '.hao123.com',
                'path' => '/'
            ],[
                'name' => 'Hm_lvt_22661fc940aadd927d385f4a67892bc3',
                'value' => $cookiesData['Hm_lvt_22661fc940aadd927d385f4a67892bc3']??'',
                'domain' => '.hao123.com',
                'path' => '/'
            ],[
                'name' => 'PC_TAB_LOG',
                'value' => $cookiesData['PC_TAB_LOG']??'',
                'domain' => '.hao123.com',
                'path' => '/'
            ],[
                'name' => 'COMMON_LID',
                'value' => $cookiesData['COMMON_LID']??'',
                'domain' => 'haokan.hao123.com',
                'path' => '/'
            ],[
                'name' => 'reptileData',
                'value' => $cookiesData['reptileData']??'',
                'domain' => 'haokan.hao123.com',
                'path' => '/'
            ],[
                'name' => 'Hm_lvt_4aadd610dfd2f5972f1efee2653a2bc5',
                'value' => $cookiesData['Hm_lvt_4aadd610dfd2f5972f1efee2653a2bc5']??'',
                'domain' => '.haokan.hao123.com',
                'path' => '/'
            ],[
                'name' => 'Hm_lpvt_4aadd610dfd2f5972f1efee2653a2bc5',
                'value' => $cookiesData['Hm_lpvt_4aadd610dfd2f5972f1efee2653a2bc5']??'',
                'domain' => '.haokan.hao123.com',
                'path' => '/'
            ],[
                'name' => 'RT',
                'value' => $cookiesData['RT']??'',
                'domain' => '.hao123.com',
                'path' => '/'
            ]);
            $page->goto($url);

            $page->waitFor('video');
            $html = $page->content();
            //$page->setViewport(['width' => 2000, 'height' => 1000]);
            $cookie = $page->evaluate(
                'document.cookie'
            );

            file_put_contents(runtime_path($fileName),$cookie);

            //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            sleep(6);
            $browser->close();

            // 返回值一定要是页面的HTML内容
            return $html;
        }, [
            'headless' => true, // 启动可视化Chrome浏览器,方便调试
            'devtools' => true, // 打开浏览器的开发者工具
            'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
        ])->getHtml();

        $fileName = 'videohtml/haokan_video_play_html.html';
        Common::mkdirs(dirname(runtime_path($fileName)));
        file_put_contents(runtime_path($fileName), $text);

        $html = file_get_contents(runtime_path($fileName));
        $ql = QueryList::html($html);
        $data = $ql->find('video')->attrs('src');
        $videoLink = $data->all()[0]??'';
        $videoLink && @unlink(runtime_path($fileName));

        return $videoLink;
    }
}